import styles from './index.module.css'
import gsap from 'gsap';
import { useLayoutEffect, useRef, useState } from "react";
import clsx from "clsx";
import Lenis from "lenis";
import leafManager from "../../lib/leafManager.js";
import {getImageDominantColorDarkened} from '../../utils/image.js';
import { usePosterStore } from "../../stores/poster.js";

const filenames = [
    'a.jpg',
    'b.jpg',
    'c.jpg',
    'd.jpg',
    'e.jpg',
    'f.jpg',
    'g.jpg',
    'h.jpg',
    'i.jpg',
    'j.jpg',
    'k.jpg',
    'l.jpg',
    'm.jpg',
    'n.jpg',
    'o.jpg',
    'p.jpg',
    'q.jpg',
    'r.jpg',
    's.jpg',
    't.jpg',
    'u.jpg',
    'v.jpg',
    'w.jpg',
    'x.jpg',
];

const prefix = './photos'

function Poster() {
    const sectionRef = useRef(null);
    const rightRef = useRef(null);
    const viewItemRef = useRef(null);
    const imgRef = useRef(null);
    const bottomLineRef1 = useRef(null);
    const bottomLineRef2 = useRef(null);

    const isFirstRender = useRef(true);
    const viewTimeline = useRef(null);
    const bottomTimeLine = useRef(null);

    const [photos, setPhotos] = useState(filenames);
    const [current, setCurrent] = useState(`demo.gif`);

    const mode = usePosterStore((state) => state.mode)

    useLayoutEffect(() => {
        if (imgRef.current) {
            // 只初始化一次 timeline
            viewTimeline.current = gsap.timeline({paused: true});
            viewTimeline.current.to(imgRef.current, {
                rotationX: 10,
                rotationY: -10,
                ease: "power2.out",
                duration: 0.5,
            });
        }
    }, []);

    const handleImageLoaded = async () => {
        if (
            bottomLineRef1.current &&
            bottomLineRef2.current &&
            imgRef.current
        ) {
            // 清空旧动画
            bottomTimeLine.current?.clear();
            bottomTimeLine.current = gsap.timeline({paused: true});

            const rect = imgRef.current.getBoundingClientRect();
            console.log(imgRef.current, rect)

            // 像素对齐
            const top1 = Math.round(rect.top + rect.height + 10);
            const top2 = Math.round(rect.top + rect.height + 20);

            const colorCss = await getImageDominantColorDarkened(imgRef.current);
            // console.log(colorCss)

            bottomLineRef1.current.style.top = `${top1}px`;
            bottomLineRef2.current.style.top = `${top2}px`;
            bottomLineRef1.current.style.backgroundColor = colorCss;
            bottomLineRef2.current.style.backgroundColor = colorCss;

            // 防止上一次动画残留宽度
            bottomLineRef1.current.style.width = '0px';
            bottomLineRef2.current.style.width = '0px';

            const end = {
                width: rect.width,
                ease: 'power2.out',
                duration: 0.2,
            };

            bottomTimeLine.current.fromTo(bottomLineRef1.current, {width: 0}, end);
            bottomTimeLine.current.fromTo(bottomLineRef2.current, {width: 0}, end);
            bottomTimeLine.current.restart();
        }
    };

    const handleView = (index) => {
        setCurrent(`${filenames[index]}`);
        imgRef.current.classList.add('viewImageAnime');
        viewTimeline.current.restart();
    }

    useLayoutEffect(() => {
        if (isFirstRender.current && rightRef.current) {
            leafManager.create(rightRef.current);
        }

        isFirstRender.current = false;
    }, []);

    useLayoutEffect(() => {
        const wrapperEl = document.querySelector(".scroll-box");
        const contentEl = document.querySelector(".scroll-content");
        const lenis = new Lenis({
            wrapper: wrapperEl,
            content: contentEl,
            smoothWheel: true,
            lerp: 0.04,
        });

        function raf(time) {
            lenis.raf(time);
            requestAnimationFrame(raf);
        }

        requestAnimationFrame(raf);

        return () => lenis.destroy();
    }, []);


    return (
        <div className={styles.wrapper}>
            <div className={clsx(styles.left, 'scroll-box')} ref={sectionRef}>
                <header className={styles.header}>
                    <span className={styles.title}>Life of PI</span>

                    <span className={styles.desc}>
                        Developer hanxiaoxin's photo site. <br/>
                        Inspired by Faint Film.
                    </span>
                </header>

                <div className={clsx(styles.photos)}>
                    <div className={clsx(styles.gridBox, 'scroll-content')}>
                        {
                            photos.map((photo, index) => {
                                return <div className={clsx(styles.photoItem)} key={`photo-${index}`}
                                            onMouseEnter={() => handleView(index)}>
                                    <span className={styles.index}>{index + 1}</span>
                                    <img src={`${prefix}/${photo}`} alt={photo} loading={"lazy"} decoding={"async"}/>
                                </div>;
                            })
                        }
                    </div>
                </div>
            </div>

            <div className={styles.right} ref={rightRef}>
                <div className={styles.viewBox}>
                    <div className={styles.viewItem} ref={viewItemRef}>
                        {
                            current ? <img onLoad={handleImageLoaded} ref={imgRef}
                                           className={clsx(".view-image", styles.viewImage)}
                                           src={`${prefix}/${current}`} alt={current}/> : ''
                        }

                        <div className={clsx(styles.bottomLine, "bl")} ref={bottomLineRef1}></div>
                        <div className={clsx(styles.bottomLine, "bl")} ref={bottomLineRef2}></div>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Poster
